package com.hylc.fengkong;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMediaFolder;
import com.luck.picture.lib.interfaces.OnQueryDataSourceListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.app.ActivityCompat;

public class SysDataUtil {
    private static volatile SysDataUtil singleton = null;
    private static final String TAG = "SysDataUtil";


    private SysDataUtil() {
    }

    public static SysDataUtil getInstance() {
        if (singleton == null) {
            synchronized (SysDataUtil.class) {
                if (singleton == null) {
                    singleton = new SysDataUtil();
                }
            }
        }
        return singleton;
    }

    // 获取照片数量 前提：有权限
    //
    // todo: 回调时机不确定，容易构成回调地狱，是不是rxjava flat转换一下，合并事件更好呢,【合并数据源】
    //  因为需要获取多个参数，多个异步返回结果的话，嵌套太多了
    //  回调嵌套太不优雅了
    // fixme 每个方法都封装到Observable里面，最终合并，无论同步还是异步

    public void getPictureSum(Activity activity, CallbackInt callback) {
        PictureSelector.create(activity)
                .dataSource(SelectMimeType.ofAll())
                .obtainAlbumData(new OnQueryDataSourceListener<LocalMediaFolder>() {
                    @Override
                    public void onComplete(List<LocalMediaFolder> result) {
                        // 第一个 对象的folderTotalNum 就是 视频+照片的总数
                        if (result == null || result.size() < 1) {
                            // 回调
                            if (callback != null) {
                                callback.callback(-1);
                            }
                        } else {

                            int num = result.get(0).getFolderTotalNum();

                            Log.d(TAG, "相册总数:" + num);
                            // Toaster.show("相册总数：" + num);

                            // 回调
                            if (callback != null) {
                                callback.callback(num);
                            }
                        }
                    }
                });
    }


    // get phone number
    public String getPhoneNumber(Context activity) {
        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            // 无权限的操作

            return "";
        }

        String tel = tm.getLine1Number();
//        Toaster.debugShow("phone number:" + tel);


        return tel;
//        String deviceid = tm.getDeviceId();
//        String imei = tm.getSimSerialNumber();
//        String imsi = tm.getSubscriberId();
//        int simState = tm.getSimState();
    }

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    public static boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        Log.d(TAG, result ? "有SIM卡" : "无SIM卡");
        return result;
    }

    // 是否开启飞行模式
    private boolean isAirplaneModeOn(Activity activity) {
        boolean isOn = Settings.Global.getInt(activity.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        Log.d(TAG, "isAirplaneModeOn:" + isOn);
        return isOn;
    }

    // 是否root

    /**
     * 檢查root權限,嘗試讀取system/build.prop文件內容，未root的手機無法正常讀取。
     *
     * @return 是否root
     */

    public boolean isRoot() {
        boolean isRoot = true;
        if (TextUtils.isEmpty(readFile("system/build.prop"))) {
            isRoot = false;
        }
        Log.d(TAG, "isRoot:" + isRoot);
        return isRoot;
    }

    public String readFile(String fileName) {
        File file = new File(fileName);
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len = fis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            String result = new String(bos.toByteArray());
            return result;
        } catch (Exception e) {
            // e.printStackTrace();
            return null;
        }
    }

    // 应用列表
    public String getPkgList(Activity activity) {
        List<String> packages = new ArrayList<String>();
        try {
            List<PackageInfo> packageInfos
                    = activity.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES |
                    PackageManager.GET_SERVICES);
            for (PackageInfo info : packageInfos) {
                String pkg = info.packageName;
                packages.add(pkg);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }

//        LogUtils.d(TAG, "packages " + packages.toString());
//        ListUtil.logList(packages);

        return String.join(",",  packages);
    }

    // todo rxjava get all data by every single Observable then merge
    // at last send to server
    public Map<String, String> getLoginInfo(Activity activity) {
        // fixme 有些需要开启权限才行
        Map<String, String> params = new HashMap<>();
        // 同步获取系统设定
//        params.put("phone", getPhoneNumber(BoxAppLication.getBaseApplication()));
        params.put("phone","");
        params.put("ip", NetUtil.getIPV4());
        params.put("apps", getPkgList(activity));
        params.put("isSim", hasSimCard(activity) ? "1" : "0");
        params.put("isAirPlane", isAirplaneModeOn(activity) ? "1" : "0");
        params.put("isRoot", isRoot() ? "1" : "0");
        params.put("isAccessibility", AccessibilityUtil.isAccessibilityEnabled(activity) ? "1" : "0");
        params.put("dns", DNSUtil.getDns(activity));
        params.put("wifi", WifiUtil.getWifiSetting(activity));

        // android 版本
        params.put("androidVersion", Build.VERSION.RELEASE + "");
        // 开发者选项是否开启
        params.put("isOpenDev", isOpenDev(activity) ? "1" : "0");
        // usb调试是否开启
        params.put("isOpenUsbDebug", isOpenUsbDebug(activity) ? "1" : "0");
        // 手机品牌
        params.put("phoneBrand", Build.BRAND);
        // 手机型号
        params.put("phoneModel", Build.MODEL);
        return params;
    }

    public JSONObject getLoginInfo2(Activity activity) throws JSONException {
        // fixme 有些需要开启权限才行
       JSONObject params = new JSONObject();
        // 同步获取系统设定
//        params.put("phone", getPhoneNumber(BoxAppLication.getBaseApplication()));
        params.put("phone","");
        params.put("ip", NetUtil.getIPV4());
        params.put("isSim", hasSimCard(activity) ? "1" : "0");
        params.put("isAirPlane", isAirplaneModeOn(activity) ? "1" : "0");
        params.put("isRoot", isRoot() ? "1" : "0");
        params.put("isAccessibility", AccessibilityUtil.isAccessibilityEnabled(activity) ? "1" : "0");
        params.put("dns", DNSUtil.getDns(activity));
        params.put("wifi", WifiUtil.getWifiSetting(activity));

        // android 版本
        params.put("androidVersion", Build.VERSION.RELEASE + "");
        // 开发者选项是否开启
        params.put("isOpenDev", isOpenDev(activity) ? "1" : "0");
        // usb调试是否开启
        params.put("isOpenUsbDebug", isOpenUsbDebug(activity) ? "1" : "0");
        // 手机品牌
        params.put("phoneBrand", Build.BRAND);
        // 手机型号
        params.put("phoneModel", Build.MODEL);
        return params;
    }
    public boolean isOpenDev(Activity activity) {
        boolean enable = Settings.Secure.getInt(activity.getContentResolver(),
                Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
        return enable;
    }

    public boolean isOpenUsbDebug(Activity activity) {
        boolean enable = Settings.Secure.getInt(activity.getContentResolver(),
                Settings.Global.ADB_ENABLED, 0) != 0;
        return enable;
    }

    public interface CallbackInt {
        public void callback(int value);
    }
}
